package com.etc.traval.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.jms.Session;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.etc.traval.biz.RoomBiz;
import com.etc.traval.biz.SellerBiz;
import com.etc.traval.biz.SellercomBiz;
import com.etc.traval.biz.UserBiz;
import com.etc.traval.bizimpl.RoomBizImpl;
import com.etc.traval.bizimpl.SellerBizImpl;
import com.etc.traval.bizimpl.SellercomBizImpl;
import com.etc.traval.bizimpl.UserBizImpl;
import com.etc.traval.pojo.SellerMoneyPojo;
import com.etc.traval.pojo.UserMoneyPojo;
import com.etc.traval.util.JDBCUtil;
import com.etc.travel.entity.Room;
import com.etc.travel.entity.Seller;
import com.etc.travel.entity.Sellercom;
import com.etc.travel.entity.User;
import com.google.gson.Gson;

public class SellerServlet extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public SellerServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);

	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		/**
		 * 查询所有商家
		 * 
		 * @author 叶圣莹
		 */
		// 获取传入的flag
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		String flag = request.getParameter("flag");
		SellerBiz sellerbiz = new SellerBizImpl();
		HttpSession session = request.getSession();
		PrintWriter out = response.getWriter();
		if (request.getParameter("flag") != null) {
			flag = request.getParameter("flag");
		}
		if (flag.equals("allseller")) {
			// 分页显示
			int size = 6;
			int page = 1;
			int count = sellerbiz.querySellerCount();
			int pageCount = (count % size == 0) ? (count / size) : (count / size + 1);
			String addpage = request.getParameter("page");
			if (addpage == null) {
				page = 1;
			} else {
				page = Integer.valueOf(addpage);
				if (page < 1) {
					page = 1;
				}
				if (page > pageCount) {
					page = pageCount;

				}
			}

		} else if (flag.equals("hotelinfo")) {
			int hotelid = Integer.valueOf(request.getParameter("hotelid"));
			SellerBiz biz = new SellerBizImpl();
			Seller seller = biz.selectSellerById(hotelid);

			SellercomBiz sellercomBiz2 = new SellercomBizImpl();

			List<Sellercom> list = sellercomBiz2.queryByUserSellercom(hotelid, 1, 5);

			RoomBiz biz3 = new RoomBizImpl();
			List<Room> list3 = biz3.queryRoomBySeller(seller);
			int count = sellercomBiz2.queryCountBySeller(seller);
			int nextindex = 2;
			int pageIndex = 1;
			int pageCount = (count % 5 == 0) ? (count / 5) : (count / 5 + 1);
			// 将list数据放入请求域
			request.setAttribute("pageCount", pageCount);
			request.setAttribute("nextindex", nextindex);
			request.setAttribute("pageIndex", pageIndex);
			request.setAttribute("list", list);
			request.setAttribute("list3", list3);
			request.setAttribute("seller", seller);
			request.getRequestDispatcher("hotelin.jsp").forward(request, response);
		} else if (flag.equals("sellerlogin")) {
			String sellerid = request.getParameter("sellerid");
			String pwd = request.getParameter("sellerpwd");
			Seller seller = sellerbiz.checkLogin(Integer.parseInt(sellerid), pwd);
			if (seller == null) {
				out.println("<script>alert('登录失败，您的密码错误，点击重新登录');location.href='sellerlogin.jsp'</script>");
			} else {
				// 将登录的用户保存到session域中

				session.setAttribute("seller", seller);
				out.println("<script>alert('登入成功');location.href='DiaryServlet?flag=toindex'</script>");
			}
			out.flush();
			out.close();
		} else if (flag.equals("queryall")) {
			List<Seller> list1 = sellerbiz.queryAllByAddkey("上海");
			List<Seller> list2 = sellerbiz.queryAllByAddkey("北京");
			List<Seller> list3 = sellerbiz.queryAllByAddkey("厦门");
			List<Seller> list4 = sellerbiz.queryAllByAddkey("杭州");
			List<Seller> list5 = sellerbiz.queryAllByAddkey("成都");
			List<Seller> list6 = sellerbiz.queryAllByAddkey("深圳");
			request.setAttribute("list1", list1);
			request.setAttribute("list2", list2);
			request.setAttribute("list3", list3);
			request.setAttribute("list4", list4);
			request.setAttribute("list5", list5);
			request.setAttribute("list6", list6);
			request.getRequestDispatcher("hotel.jsp").forward(request, response);

		} else if (flag.equals("searchhotel")) {
			request.setCharacterEncoding("utf-8");
			response.setContentType("text/html;charset=utf-8");
			String key = request.getParameter("key");
			List<Seller> list = sellerbiz.queryAllByAddkey(key);
			List<Seller> list1 = sellerbiz.queryAllByAddkey("上海");
			List<Seller> list2 = sellerbiz.queryAllByAddkey("北京");
			List<Seller> list3 = sellerbiz.queryAllByAddkey("厦门");
			List<Seller> list4 = sellerbiz.queryAllByAddkey("杭州");
			List<Seller> list5 = sellerbiz.queryAllByAddkey("成都");
			List<Seller> list6 = sellerbiz.queryAllByAddkey("深圳");
			request.setAttribute("list", list);
			String name = null;
			if (list.size() == 0) {
				name = "没有搜索到您查询的酒店";
			} else {
				name = "根据“" + key + "”搜索到的酒店：";
			}
			request.setAttribute("key", name);
			request.setAttribute("list1", list1);
			request.setAttribute("list2", list2);
			request.setAttribute("list3", list3);
			request.setAttribute("list4", list4);
			request.setAttribute("list5", list5);
			request.setAttribute("list6", list6);
			request.getRequestDispatcher("hotel.jsp").forward(request, response);

		} else if (flag.equals("loginout")) {
			// 退出登录的servlet
			// 将session设置失效
			request.getSession().invalidate();
			response.sendRedirect("login.jsp");
		} else if (flag.equals("sellerregister")) {

			String name = request.getParameter("username");
			String pwd = request.getParameter("userpwd");
			String tel = request.getParameter("usertel");
			String addr = request.getParameter("useraddr");
			SellerBiz biz = new SellerBizImpl();
			Seller seller = new Seller();
			seller.setSeller_name(name);
			seller.setSeller_pwd(pwd);
			seller.setSeller_money(0.0);
			seller.setSeller_tel(tel);
			seller.setSeller_logo("imgage/userlogo0");
			seller.setSeller_addr(addr);
			seller.setSeller_synopsis("");
			if (1 == biz.checksellertel(tel)) {
				out.print("<script>alert('注册失败，此电话已经被注册了');location.href='register.jsp';</script>");
			} else {
				if (biz.AddSeller(seller)) {
					request.getSession().setAttribute("seller", seller);
					Seller seller1 = biz.querySellerBytel(tel);
					int sellerid = seller1.getSeller_id();
					out.println("<script>alert('注册成功，恭喜你成为蜂窝煤商家圈一份子，你的商家号为：" + sellerid
							+ "');location.href='sellerlogin.jsp';</script>");
				} else {
					out.println("<script>alert('注册失败');location.href='register.jsp';</script>");
				}
			}
			out.flush();
			out.close();
		} else if (flag.equals("updateinfo")) {
			String name = request.getParameter("sname");
			String addr = request.getParameter("saddr");
			String tel = request.getParameter("stel");
			String synopsis = request.getParameter("ssy");
			int sellerid = Integer.valueOf(request.getParameter("sellerid"));
			if (name != "") {
				if (addr != "") {
					if (tel != "") {
						if (synopsis != "") {
							if (sellerbiz.updateAllById(name, addr, tel, synopsis, sellerid)) {
								Seller seller = sellerbiz.selectSellerById(sellerid);
								session.setAttribute("seller", seller);
								out.println("<script>alert('修改成功');location.href='SellerManage.jsp';</script>");
							} else {
								out.println("<script>alert('修改失败');location.href='SellerManage.jsp';</script>");
							}
						} else {
							out.println("<script>alert('简介不能为空');location.href='SellerManage.jsp';</script>");
						}
					} else {
						out.println("<script>alert('电话不能为空');location.href='SellerManage.jsp';</script>");
					}
				} else {
					out.println("<script>alert('地址不能为空');location.href='SellerManage.jsp';</script>");
				}
			} else {
				out.println("<script>alert('商家名不能为空');location.href='SellerManage.jsp';</script>");
			}
			out.flush();
			out.close();
		} else if (flag.equals("queryroom")) {
			RoomBiz roombiz = new RoomBizImpl();
			Seller seller = sellerbiz.selectSellerById(Integer.valueOf(request.getParameter("sellerid")));
			List<Room> list = roombiz.queryAll(seller);
			Gson gson = new Gson();
			String jsonString = gson.toJson(list);
			response.setContentType("text/html;charset=utf-8");
			;
			out.print(jsonString);
			out.flush();
			out.close();
		} else if (flag.equals("updatepwd")) {
			String pwd1 = request.getParameter("oldpwd");
			String pwd2 = request.getParameter("newpwd");
			Seller seller = (Seller) request.getSession().getAttribute("seller");
			String mypwd = seller.getSeller_pwd();
			SellerBiz biz = new SellerBizImpl();
			if (mypwd.equals(pwd1)) {
				if (biz.updatePwd(pwd2, seller.getSeller_id())) {
					out.print("<script>alert('密码已修改,请重新登录');location.href='login.jsp'</script>");
				} else {
					out.print("<script>alert('修改失败');location.href='SellerManage.jsp'</script>");
				}
			} else {
				out.print("<script>alert('修改失败，原密码错误');location.href='SellerManage.jsp'</script>");
			}
			out.flush();
			out.close();

		}else if(flag.equals("getmoneypojo")){
			JDBCUtil util = new JDBCUtil();
			int userid = Integer.parseInt(request.getParameter("userid"));
			SellerMoneyPojo sellerMoneyPojo = new SellerMoneyPojo();
			ResultSet rs1=util.query("select sum(order_money) as money from t_order where order_endtime like '%1月%' and order_seller=?",userid);
			ResultSet rs2=util.query("select sum(order_money) as money from t_order where order_endtime like '%2月%' and order_seller=?",userid);
			ResultSet rs3=util.query("select sum(order_money) as money from t_order where order_endtime like '%3月%' and order_seller=?",userid);
			ResultSet rs4=util.query("select sum(order_money) as money from t_order where order_endtime like '%4月%' and order_seller=?",userid);
			ResultSet rs5=util.query("select sum(order_money) as money from t_order where order_endtime like '%5月%' and order_seller=?",userid);
			ResultSet rs6=util.query("select sum(order_money) as money from t_order where order_endtime like '%6月%' and order_seller=?",userid);
			try {
				if(rs1.next()){
					sellerMoneyPojo.setJan(rs1.getDouble("money"));
				}else {
					sellerMoneyPojo.setJan(0);
				}
				if(rs2.next()){
					sellerMoneyPojo.setFed(rs2.getDouble("money"));
				}else {
					sellerMoneyPojo.setFed(0);
				}
				if(rs3.next()){
					sellerMoneyPojo.setMar(rs3.getDouble("money"));
				}else {
					sellerMoneyPojo.setMar(0);
				}
				if(rs4.next()){
					sellerMoneyPojo.setApr(rs4.getDouble("money"));
				}else {
					sellerMoneyPojo.setApr(0);
				}
				if(rs5.next()){
					sellerMoneyPojo.setMay(rs5.getDouble("money"));
				}else {
					sellerMoneyPojo.setMay(0);
				}
				if(rs6.next()){
					sellerMoneyPojo.setJun(rs6.getDouble("money"));
				}else {
					sellerMoneyPojo.setJun(0);
				}
			}catch (SQLException e) {
				e.printStackTrace();
			}finally {
				util.closeAll();
			}
			Gson gson=new Gson();
		    String jsonString= gson.toJson(sellerMoneyPojo);
		    response.setContentType("text/html;charset=utf-8");;
		    out.print(jsonString);
		    out.flush();
		    out.close();
		}

	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
